import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import isBetween from 'dayjs/plugin/isBetween';
import relativeTime from 'dayjs/plugin/relativeTime';
dayjs.extend(relativeTime);
dayjs.extend(duration);
dayjs.extend(isBetween);

const DayType = {
  0: '周日',
  1: '周一',
  2: '周二',
  3: '周三',
  4: '周四',
  5: '周五',
  6: '周六',
};

export const fmtDate = (t) => t.format('YYYYMMDD');
export const fmtShortDate = (t) => t.format('MM-DD');
export const fmtShortDateTime = (t) => t.format('MM-DD HH:mm');
export const fmtLongDate = (t) => t.format('YYYY-MM-DD');
export const fmtLongDateTime = (t) => t.format('YYYY-MM-DD HH:mm:ss');
export const fmtLongTime = (t) => t.format('HH:mm:ss');

export const tsDuration = (t) => dayjs.duration(t, 'milliseconds').humanize();
export const tsToNow = (t) => dayjs(t).toNow();
export const tsIsBetween = (now, a, b) => dayjs(now).isBetween(a, b);
export const tsIsBefore = (t) => dayjs().isBefore(dayjs(t));
export const tsFromNow = (t) => dayjs(t).fromNow();
export const tsFmtDate = (timeStamp) => fmtDate(dayjs(timeStamp));
export const tsFmtShortDate = (timeStamp) => fmtShortDate(dayjs(timeStamp));
export const tsFmtShortDateTime = (timeStamp) =>
  fmtShortDateTime(dayjs(timeStamp));
export const tsFmtLongDate = (timeStamp) => fmtLongDate(dayjs(timeStamp));
export const tsFmtLongDateTime = (timeStamp) =>
  fmtLongDateTime(dayjs(timeStamp));
export const tsFmtLongFromNow = (t) =>
  `${tsFmtLongDateTime(t)} (${dayjs().from(t, true)})` || '-';

export const strFmtLongDateTime = (s) => dayjs(s).format('YYYY-MM-DD HH:mm:ss');

export const today = () => dayjs();
export const yesterday = () => dayjs().subtract(1, 'days');
export const pastDay = (n) => dayjs().subtract(n, 'days');
export const afterDay = (n) => dayjs().add(n, 'days');
export const fmtDay = (n) => DayType[dayjs(n).day()];
export const untilToday = (t) => t && t >= dayjs().startOf('day');
export const locale = (s) => dayjs.locale(s);

export const formatDuration = (mss) => {
  const days = parseInt(mss / (1000 * 60 * 60 * 24));
  const hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((mss % (1000 * 60)) / 1000);
  return (
    days + ' 天 ' + hours + ' 小时 ' + minutes + ' 分钟 ' + seconds + ' 秒 '
  );
};
